<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    // 封装一个函数，作用和 axios 一样

    function ajax({ method, url, params, data }) {
      return new Promise ((resolve,reject)=>{
        let arr = []
      for (let key in params) {
        arr.push(`${key}=${params[key]}`)
      }

      const xhr = new XMLHttpRequest()

      xhr.addEventListener('load', function () {
        if (xhr.status >= 200 && xhr.status < 300) {
          console.log( JSON.parse(xhr.response))
        } else if (xhr.status >= 300) {
          console.log( JSON.parse(xhr.response))
        }
      })

      xhr.open(method, url + '?' + arr.join('&'))

      if (typeof data === 'string') {
        // 说明提交的是查询字符串
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        xhr.send(data)
      } else if (data instanceof FormData) {
        // 说明提交的是FormData对象
        xhr.send(data)
      } else if (data instanceof Object) {
        // 说明提交的是字面量对象
        xhr.setRequestHeader('Content-Type', 'application/json')
        xhr.send(JSON.stringify(data))
      } else {
        xhr.send()
      }
      })
    }

    // 使用的话，和axios一样
    ajax({
      method: 'GET',
      url: 'http://www.itcbc.com:3006/api/getbooks',
      params: {
        appkey: 'xiaoxu'
      }
    }).then(all =>{
      console.log(all);
    })

    ajax({
      method: 'POST',
      url: 'http://www.itcbc.com:3006/api/addbook',
      data: {
        bookname: '西游记',
        author: '吴承恩',
        publisher: '北京出版社',
        appkey: 'xiaoxu'
      }
    }).then(all =>{
      console.log(all);
    })
  </script>
</body>

</html>